package com.ruoyi.task;

import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.core.domain.dto.DownloadVideoDTO;
import com.ruoyi.common.core.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

import static com.ruoyi.hkCamera.config.AlarmConfig.hCNetSDK;

@Slf4j
@Component
@EnableScheduling
public class DownloadFileTask {

    @Autowired
    private RedisCache redisCache;

    @Value("${scheduling.enabled.checkVideoDownload:false}")
    private boolean schedulingEnabledCheckVideoDownload; // 从配置文件读取定时任务是否启用

    /**
     * 视频是否下载完成
     */
    @Scheduled(fixedRate = 600)
    public void checkVideoDownload() {
        if (!schedulingEnabledCheckVideoDownload) {
            return;
        }
        if (redisCache.hasKey("downloadVideo")) {
            Map<String, DownloadVideoDTO> dataMap = redisCache.getCacheMap("downloadVideo");
            dataMap.forEach((hPlayback, dto) -> {
                int ihPlayback = Integer.parseInt(hPlayback);
                log.info("过车视频下载 检查 checkNo：{}, hPlayback：{}", dto.getCheckNo(), hPlayback);
                int downloadPos = hCNetSDK.NET_DVR_GetDownloadPos(ihPlayback);
                if (downloadPos > 100) {
                    redisCache.deleteCacheMapValue("downloadVideo", hPlayback);
                    log.error("过车视频下载 由于网络原因或DVR忙,下载异常终止!" + hCNetSDK.NET_DVR_GetLastError());
                }
                if (downloadPos == 100) {
                    redisCache.deleteCacheMapValue("downloadVideo", hPlayback);
                    hCNetSDK.NET_DVR_StopGetFile(ihPlayback);
                    log.info("过车视频下载 结束 checkNo：{}, 结束时间：{}", dto.getCheckNo(), DateUtil.now());
                }
            });
        }
    }

}
